package com.engineering.elink.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.engineering.elink.co.BaseCo;
import com.engineering.elink.common.ErrorType;
import com.engineering.elink.common.Pagination;
import com.engineering.elink.domain.Course;
import com.engineering.elink.domain.VideoCollection;
import com.engineering.elink.service.VideoCollectionService;
import com.engineering.elink.util.ResJsonUtil;
import com.engineering.elink.videodao.CourseMapper;
import com.engineering.elink.videodao.LabelMapper;
import com.engineering.elink.videodao.VideoCollectionMapper;
import com.engineering.elink.vo.VideoCollectionVo;

@Service
public class VideoCollectionServiceImpl implements VideoCollectionService {
	
	@Autowired
	private VideoCollectionMapper videoCollectionMapper;
	
	@Autowired
	private CourseMapper courseMapper;
	
	@Autowired
	private LabelMapper labelMapper;
	

	@Override
	public Map<String, Object> updateCollect(String userId, Integer courseId) {
		if(StringUtils.isEmpty(userId)){
			return ResJsonUtil.getMap(ErrorType.USERINFO_ERROR);
		}
		
		Course f = courseMapper.selectByPrimaryKey(courseId);
		if(f != null ){
			int count = videoCollectionMapper.select(userId,courseId);
			if(count == 0 ){ //表示没有收藏过
				VideoCollection c = new VideoCollection();
				c.setUserId(userId);
				c.setCourseId(courseId);
				c.setCollectionTime(new Date());
				videoCollectionMapper.insertSelective(c);
				//课程的收藏数加一
				f.setCollectionCount(f.getCollectionCount()+1);
				courseMapper.updateByPrimaryKeySelective(f);
				
				return ResJsonUtil.getMap(ErrorType.COLLECTION_SUCCESS);
			}else{
				videoCollectionMapper.deleteByCollection(userId,courseId);
				//课程的收藏数减1
				f.setCollectionCount(f.getCollectionCount()-1);
				courseMapper.updateByPrimaryKeySelective(f);
				
				return ResJsonUtil.getMap(ErrorType.CANCEL_COLLECTION);
			}
			
		}else{
			return ResJsonUtil.getMap(ErrorType.COURSE_COLLECTION_ERROR);
		}
		
	}

	@Override
	public Map<String, Object> getMyCollect(BaseCo co,String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<VideoCollectionVo> vcList=courseMapper.getMyCollect(co,userId);
		for (VideoCollectionVo vo : vcList) {
			vo.setLabelList(labelMapper.getLabelList(vo.getLabelIds()));
		}
		map.put("list", vcList);
		map.put("Pagination", new Pagination(co, courseMapper.selectCountMyCollect(userId)));
		
		return map;
	}

}
